/**
 * GWT Kad : Kademlia implementation for GWT
 * Copyright (C) 2012  Pierrick HYMBERT, Paul-André MISTRAL, Florian ALEXANDRE
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 * 
 */
package org.kad.gwt.web.client.transport.http.mvp.error;

import com.google.gwt.event.shared.EventHandler;
import com.google.gwt.event.shared.GwtEvent;

/**
 * Fired when the event source receive an error from the http server.
 * @author Pierrick HYMBERT &lt;pierrick [dot] hymbert [at] gmail [dot] com&gt;
 */
public class HttpServerErrorEvent extends GwtEvent<HttpServerErrorEvent.Handler> {
    public interface Handler extends EventHandler {
        void onHttpServerError(HttpServerErrorEvent event);
    }
    /**
     * The event type.
     */
    static Type<HttpServerErrorEvent.Handler> TYPE;

    /**
     * Fires an {@link HttpServerErrorEvent} on all registered handlers in the handler
     * source.
     *
     * @param <S> The handler source type
     * @param source the source of the handlers
     * @param errorMessage {@link #errorMessage}
     */
    public static <S extends HasHttpServerErrorHandlers> void fire(S source, String errorMessage) {
      if (TYPE != null) {
          HttpServerErrorEvent event = new HttpServerErrorEvent(errorMessage);
          source.fireEvent(event);
      }
    }

    /**
     * Ensures the existence of the handler hook and then returns it.
     *
     * @return returns a handler hook
     */
    public static Type<HttpServerErrorEvent.Handler> getType() {
      if (TYPE == null) {
        TYPE = new Type<HttpServerErrorEvent.Handler>();
      }
      return TYPE;
    }
    /**
     * The associated error message.
     */
    private final String errorMessage;

    /**
     * Construct a new {@link HttpServerErrorEvent}.
     */
    protected HttpServerErrorEvent(String errorMessageIn) {
        this.errorMessage = errorMessageIn;
    }
    
    /**
     * @return {@link #errorMessage}
     */
    public String getErrorMessage() {
        return errorMessage;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public final Type<HttpServerErrorEvent.Handler> getAssociatedType() {
      return TYPE;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void dispatch(HttpServerErrorEvent.Handler handler) {
      handler.onHttpServerError(this);
    }
}
